<template>
  <div v-if="visible2" class="dialog-overlay">
    <div class="dialog">
      <!-- 头部 -->
      <div class="dialog-header">
        <h3>解答题</h3>
        <button @click="handleClose">×</button>
      </div>
      
      <!-- 内容 -->
      <div class="dialog-body">
        <div v-if="loading">生成题目中...</div>
        <div v-else>
          <div v-for="(q, i) in quiz.answerquestion" :key="i" class="question">
            <h4>{{ i+1 }}. {{ q.header }}
              <button @click="logQuestion(q,i)" class="log-button">加入收藏</button>
            </h4>
            <!-- answers[i] -->
            <textarea
              v-model="q.youranswer"
              :placeholder="'请输入答案（限200字）'"
              rows="3"
              maxlength="200"
              class="answer-input"
            ></textarea>
            <div v-if="getscore" >
  本题得分<span :class="{'green-text': scores[i] >= 60, 'red-text': scores[i] < 60}">{{scores[i]}}</span>/100
</div>
            <div v-if="Answervisible">
                <h4>
                    正确答案是：{{q.rightanswer}}
                </h4>
            </div>
            <!-- <button @click="logQuestion(q)" class="log-button">Log Question</button> -->
          </div>
        </div>
      </div>
      
      <!-- 底部 -->
      <div class="dialog-footer">
        <button @click="handleSubmit">提交</button>
      </div>
    </div>
    
    <!-- 关闭确认弹框 -->
    <div v-if="showCloseConfirm" class="confirm-dialog">
      <p>确定要关闭吗？未提交的答案将丢失</p>
      <button @click="confirmClose">确定</button>
      <button @click="showCloseConfirm = false">取消</button>
    </div>
  </div>
  <!-- 添加判题中弹窗 -->
  <div v-if="judging" class="judging-overlay">
    <div class="judging-content">
      <div class="judging-spinner"></div>
      <p>判题中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { generateAnswerQuestions } from '@/api/modules/axiosApi'
import { ElMessage } from 'element-plus'
import {insertAnswerQuestion} from '@/api/modules/axiosApi'
import {getscores} from '@/api/modules/axiosApi'
import {insertWAnswerQuestions} from '@/api/modules/axiosApi'
import { useUserStore } from '@/stores/userStore'

const props = defineProps({
  visible2: Boolean,
  num: Number,
  questionclass: String
})

const emit = defineEmits(['update:visible2', 'submit'])
let prompt=''
const quiz = ref(null)
const loading = ref(false)
const answers = ref([])
const showCloseConfirm = ref(false)
const Answervisible=ref(false)
const loggedQuestions = ref(new Set())
const getscore=ref(false)
const scores=ref([])
const answerquestion=ref({})
const judging = ref(false) // 新增判题状态
// 生成题目
watch(() => props.visible2, async (visible2) => {
  if (visible2) {
    loading.value = true
    try {
      const res = await generateAnswerQuestions(props.num, props.questionclass)
      quiz.value = res.data
      answers.value = new Array(props.num).fill('')
       loggedQuestions.value.clear() // 每次打开对话框时清空记录
//        console.log(quiz.value.answerquestion
// )
       
    } finally {
      loading.value = false
    }
  }
})

// 关闭处理
const handleClose = () => {
  if (answers.value.some(a => a !== '')) {
    showCloseConfirm.value = true
  } else {
    emit('update:visible2', false)
  }
  scores.value=[]
  Answervisible.value=false
console.log(quiz.value);

}

const confirmClose = () => {
  showCloseConfirm.value = false
  emit('update:visible2', false)
}
// 打印题目方法
const logQuestion = (question, index) => {
  prompt=props.questionclass 
  const userStore =useUserStore() 
  let wronganswerquestion={}
  if (loggedQuestions.value.has(index)) {
     alert('这道题已经收藏过了，不能重复收藏！')
    return
  }
  
  console.log(JSON.stringify({
    header: question.header,
    // answerschoice: question.answerschoice,
    rightanswer: question.rightanswer
  }, null, 2))
wronganswerquestion.header=question.header
wronganswerquestion.rightanswer=question.rightanswer
wronganswerquestion.user_id=userStore.user.id
wronganswerquestion.prompt=prompt
  insertAnswerQuestion(wronganswerquestion)
  loggedQuestions.value.add(index) 
  alert('收藏成功')
}

// 提交处理
const handleSubmit = async() => {
 if (getscore.value) {
    ElMessage.warning('您已经提交过答案了，不能重复提交')
    return
  }
const userStore =  useUserStore()
prompt=props.questionclass 
if (confirm('确定要提交答案吗？')) {
    judging.value = true // 开始判题，显示弹窗
    Answervisible.value = true
    getscore.value = false // 先隐藏分数
    
    try {
      emit('submit', { quiz: quiz.value, answers: answers.value })
      
      const questionsArray = quiz.value.answerquestion.map(q => ({
        header: q.header,
        rightanswer: q.rightanswer,
        youranswer: q.youranswer
        
      }))
      
      //console.log(questionsArray)
      const response = await getscores(questionsArray)
      scores.value = Array.isArray(response) ? response : []
      //console.log(scores.value)
      
      const wronganswerquestion = quiz.value.answerquestion
        .filter((_, index) => scores.value[index] < 60)
        .map(q => ({
          header: q.header,
          rightanswer: q.rightanswer,
          user_id:userStore.user.id,
          prompt:prompt
        }));
      
      //console.log('60分以下的题目:', wronganswerquestion);
      insertWAnswerQuestions(wronganswerquestion)
      getscore.value = true // 显示分数
    } catch (error) {
      ElMessage.error('判题失败: ' + error.message)
    } finally {
      judging.value = false // 无论成功失败都关闭弹窗
    }
  }
  console.log(quiz.value);
  
}
</script>

<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
   z-index: 9999; 
}

.dialog {
  background: white;
  width: 600px;
  max-width: 90%;
  max-height: 80vh;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.dialog-body {
  padding: 16px;
  overflow-y: auto;
  flex-grow: 1;
}

.question {
  margin-bottom: 20px;
}

.answer-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
}

.dialog-footer {
  padding: 16px;
  border-top: 1px solid #eee;
  text-align: right;
}

.confirm-dialog {
  position: fixed;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.2);
}
.log-button {
  margin-top: 8px;
  padding: 4px 8px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.log-button:hover {
  background-color: #e0e0e0;
}
.green-text {
  color: #67C23A; /* Element Plus 的成功绿色 */
  font-weight: bold;
}

.red-text {
  color: #F56C6C; /* Element Plus 的错误红色 */
  font-weight: bold;
}
.judging-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10000;
}

.judging-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.judging-spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>